#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

int serv_listen(const char *name);
int serv_accept(int listenfd, uid_t *uidptr);
int cli_conn(const char *name);
int send_fd(int fd, int fd_to_send);
int recv_fd(int fd, uid_t *uidptr, ssize_t (*userfunc)(int, const void *, size_t));

int main(int argc, char *argv[])
{
    int listenfd, connfd, fd;
    char buf[10];
    uid_t uid;

    if (fork() == 0) {
        listenfd = serv_listen("foo.socket");
        if (listenfd > 0)
            printf("child: serv_listen success at %d\n", listenfd);
        else
            printf("child: serv_listen error at %d\n", listenfd);

        connfd = serv_accept(listenfd, NULL);
        if (connfd > 0)
            printf("child: serv_accept success at %d\n", connfd);
        else
            printf("child: serv_accept error at %d\n", connfd);

        fd = recv_fd(connfd, &uid, write);
        if (fd >= 0)
            printf("child: receive fd %d\n", fd);
        else
            printf("child: not receive fd %d\n", fd);

        lseek(fd, 0, SEEK_SET);
        read(fd, buf, 10);
        printf("child: receive %s\n", buf);
        exit(0);
    }

    sleep(1);
    connfd = cli_conn("foo.socket"); 
    if (connfd > 0)
        printf("parent: connect success at %d\n", connfd);
    else
        perror("cli_conn error");

    fd = open("hello", O_RDWR|O_CREAT, 0600);
    write(fd, "123", 4);

    if (send_fd(connfd, fd) == 0)
        printf("parent: send fd %d success\n", fd);
    else
        perror("send_fd error");
   
    close(fd);
    wait(NULL);

    return 0;
}
